<template>
  <div class="hello">
    <!-- 1. 必须要有rules属性 -->
    <el-form :model="loginForm" :rules="rules" label-width="100px" ref="loginRef">
      <!-- 2. prop中的字段必须和表单对象里面的字段保持一致 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="loginForm.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="loginForm.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button
        >
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/api/user'
export default {
  data () {
    // 参数只用value，表示用户输入的值
    const checkPwd = (rule, value, callback) => {
      if (value.trim() === '') {
        return callback(new Error('密码不能为空'))
      }
      const regPwd = /[0-9A-Za-z]{5,}/
      if (regPwd.test(value)) {
        // 测试通过
        callback()
      } else {
        callback(new Error('密码6位的数字字母'))
      }
    }
    return {
      loginForm: {
        username: 'admin',
        password: 'admin'
      },
      rules: {
        // 2.校验规则中的字段必须和表单对象里面的字段保持一致
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { validator: checkPwd, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      // 先得去获取登录的校验是否通过，通过了才能发请求
      this.$refs.loginRef.validate(async (valid) => {
        if (valid) {
          const res = await login({
            name: this.loginForm.username,
            password: this.loginForm.password
          })
          if (res.data.success_code === 200) {
            // 应该调用方法，将res.data放在vuex里面
            this.$store.commit('updateUserinfo', res.data.data)
            localStorage.setItem('token', 'Bearer ' + res.data.token)
            this.$router.push({ name: 'user_manage' })
          }
        } else {
          this.$message('这是一条消息提示')
          return false
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
